# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.db.models import Max

from wlmodels.codes.dicts import ca14_dict, ca26_dict, ca27_dict, cb16_dict, cb17_dict, cb30_dict, cb31_dict, cb32_dict, cd04_dict, \
    cd16_dict, cf01_dict, ex01_dict, ex19_dict, ex02_dict
from wlmodels.codes.fields import CrossForeignCharField
from wlmodels.codes.models import ELBaseModel, ELRegion, ELCA02, ELCA11, ELCA25, ELCA12, ELCA16, EntIdable


# 个体户基本信息
class ELGeti(ELBaseModel):
    entid = models.IntegerField('个体户UID', unique=True)
    ENTNAME = models.CharField('个体户名称', max_length=100, null=True, blank=True, db_index=True)
    REGNO = models.CharField('主体注册号', max_length=30, null=True, blank=True, db_index=True)
    ORIREGNO = models.CharField('原注册号', max_length=30, null=True, blank=True)
    ENTTYPE_id = CrossForeignCharField('商户类型', max_length=4, null=True, blank=True, db_column='ENTTYPE')
    INDUSTRYPHY = models.CharField('行业门类', max_length=1, null=True, blank=True)
    INDUSTRYCO = models.CharField('行业代码', max_length=4, null=True, blank=True)
    ABUITEM = models.TextField('许可经营项目', null=True, blank=True)
    CBUITEM = models.TextField('一般经营项目', null=True, blank=True)
    OPFROM = models.DateField('经营(驻在)期限自', null=True, blank=True)
    OPTO = models.DateField('经营(驻在)期限至', null=True, blank=True)
    POSTALCODE = models.CharField('邮政编码', max_length=6, null=True, blank=True)
    TEL = models.CharField('联系电话', max_length=30, null=True, blank=True)
    EMAIL = models.EmailField('E-mail', null=True, blank=True)
    ESDATE = models.DateField('成立日期', null=True, blank=True, db_index=True)
    APPRDATE = models.DateField('核准日期', null=True, blank=True)
    REGORG_id = CrossForeignCharField('登记机关', db_column='REGORG', max_length=6, null=True, blank=True)
    ENTSTATUS = models.CharField('经营状态', max_length=1, null=True, blank=True, choices=ex02_dict)
    REGCAP = models.FloatField('注册资金（元）', null=True, blank=True, db_index=True)
    OPSCOANDFORM = models.TextField('经营范围及方式', null=True, blank=True)
    OPLOC = models.CharField('经营场所', max_length=200, null=True, blank=True)
    OPLOCDISTRICT_id = CrossForeignCharField('经营场所所在行政区划', db_column='OPLOCDISTRICT', max_length=6, null=True, blank=True)
    EMPNUM = models.FloatField('从业人数', null=True, blank=True)
    LOCALADM_id = CrossForeignCharField('属地监管工商所', db_column='LOCALADM', max_length=10, null=True, blank=True)
    CREDLEVEL = models.CharField('信用等级', max_length=1, null=True, blank=True, choices=cf01_dict)
    ASSDATE = models.DateField('分类日期', null=True, blank=True)
    ENTCAT = models.CharField('主体分类码', max_length=2, null=True, blank=True, choices=ca14_dict,
                              help_text='该字段内容在总局做整合。不是标准代码，根据地方实际情况增加的。')
    SCONFORM = models.CharField('组成形式', max_length=2, null=True, blank=True, choices=ca27_dict,
                                help_text='对个人独资企业基本信息来说，该指标表示出资方式（个独）EX03，1、以个人财产出资，2、以家庭共有财产作为个人出资；对个体基本信息来说，对应组成形式COMPFORM（来自标准代码CA27）')
    MANACATE = models.CharField('经营类别', max_length=4, null=True, blank=True, choices=ex19_dict)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户信息'
        verbose_name_plural = '个体户信息'
        app_label = "company"
        db_table = 'geti_basic'

    def __unicode__(self):
        if self.ENTNAME:
            return u'%s' % self.ENTNAME
        else:
            return u'%s' % self.entid

    def save(self, *args, **kwargs):
        # 自动分配新的entid
        if not self.entid:
            the_max = ELGeti.objects.all().aggregate(Max('entid'))
            self.entid = int(the_max['entid__max']) + 1
        super(ELGeti, self).save(*args, **kwargs)

    def _enttype(self):
        the_enttype = list(ELCA16.objects.filter(code=self.ENTTYPE_id).values_list("name", flat=True))
        if len(the_enttype):
            return the_enttype[0]
        return ""

    _enttype.short_description = "企业类型"

    ENTTYPE = property(_enttype)

    def _regorg(self):
        the_regorg = list(ELCA11.objects.filter(code=self.REGORG_id).values_list("name", flat=True))
        if len(the_regorg):
            return the_regorg[0]
        return ""

    _regorg.short_description = "登记机关"

    REGORG = property(_regorg)

    def _oplocdistrict(self):
        return ELRegion.get_region(self.OPLOCDISTRICT_id)

    _oplocdistrict.short_description = "经营场所所在行政区划"

    OPLOCDISTRICT = property(_oplocdistrict)

    def _localadm(self):
        the_localadm = list(ELCA12.objects.filter(code=self.LOCALADM_id).values_list("name", flat=True))
        if len(the_localadm):
            return the_localadm[0]
        return ""

    _localadm.short_description = "属地监管工商所"

    LOCALADM = property(_localadm)

    # 从管理人员表获取法人信息
    def _faren(self):
        the_faren = list(ELGetiPerson.objects.filter(entobj=self.entid).values_list("NAME", flat=True))
        if len(the_faren):
            return the_faren[0]
        return ""

    _faren.short_description = "法定代表人"

    faren = property(_faren)

    # 从管理人员表获取法人电话
    def _farentel(self):
        the_farentel = list(ELGetiPerson.objects.filter(entobj=self.entid).values_list("TEL", flat=True))
        if len(the_farentel):
            return the_farentel[0]
        return ""

    _farentel.short_description = "法人电话"

    farentel = property(_farentel)


# 个体经营者基本信息
class ELGetiPerson(ELBaseModel):
    entobj = models.ForeignKey('company.ELGeti', verbose_name='所属个体户', db_column='entid', default=0,
                               related_name='c_geti_person', to_field='entid')
    personid = models.ForeignKey('company.ELPerson', verbose_name='关联个人', db_column='personid', null=True, blank=True,
                                 related_name='p_geti_person', to_field='personid', default=0)
    NAME = models.CharField('姓名', max_length=200, null=True, blank=True)
    CERNO = models.CharField('证件号码', max_length=30, null=True, blank=True, db_index=True)
    CERTYPE = models.CharField('证件类型', max_length=2, null=True, blank=True, choices=cb16_dict)
    SEX = models.CharField('性别', max_length=1, null=True, blank=True, choices=cb17_dict)
    LITDEG = models.CharField('文化程度', max_length=3, null=True, blank=True, choices=cb31_dict)
    NATION = models.CharField('民族', max_length=3, null=True, blank=True, choices=cb32_dict)
    POLSTAND = models.CharField('政治面貌', max_length=3, null=True, blank=True, choices=cb30_dict)
    DOM = models.CharField('住所', max_length=100, null=True, blank=True)
    POSTALCODE = models.CharField('邮政编码', max_length=6, null=True, blank=True)
    TEL = models.CharField('联系电话', max_length=30, null=True, blank=True)
    OCCST = models.TextField('职业状况', null=True, blank=True)
    OPERAREA_id = CrossForeignCharField('经营者所在地区', max_length=6, db_column='OPERAREA', null=True, blank=True)
    CERISSDATE = models.DateField('证件签发日期', null=True, blank=True)
    CHARACTER = models.CharField('经营者主体特征', max_length=3, null=True, blank=True, choices=ex01_dict)
    COUNTRY_id = CrossForeignCharField('国别(地区)', max_length=3, null=True, blank=True, db_column='COUNTRY')
    CERVALPER = models.DateField('证件有效期', null=True, blank=True)
    NOTORG = models.CharField('身份核证文件核(公)证机构(人)', max_length=100, null=True, blank=True)
    NOTDOCNO = models.CharField('身份核证文件编号', max_length=50, null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户负责人'
        verbose_name_plural = '个体户负责人'
        app_label = "company"
        db_table = 'geti_person'

    def _entid(self):
        entid = ELGeti.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self):
        return u'%s的负责人' % self.entid

    def _operarea(self):
        the_operarea = list(ELCA02.objects.filter(code=self.OPERAREA_id).values_list("name", flat=True))
        if len(the_operarea):
            return the_operarea[0]
        return ""

    _operarea.short_description = "经营者所在地区"

    OPERAREA = property(_operarea)

    def _country(self):
        the_country = list(ELCA02.objects.filter(code=self.COUNTRY_id).values_list("name", flat=True))
        if len(the_country):
            return the_country[0]
        return ""

    _country.short_description = "国别(地区)"

    COUNTRY = property(_country)


# 个体户吊销信息
class ELGetiRevoke(ELBaseModel):
    entobj = models.ForeignKey('company.ELGeti', verbose_name='所属个体户', db_column='entid', default=0,
                               related_name='c_geti_revoke', to_field='entid')
    REVDATE = models.DateField('吊销日期', null=True, blank=True)
    ILLEGACT = models.TextField('违法行为', null=True, blank=True)
    REVBASIS = models.TextField('吊销依据', null=True, blank=True)
    ISCAN = models.NullBooleanField('是否注销', blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户吊销信息'
        verbose_name_plural = '个体户吊销信息'
        app_label = "company"
        db_table = 'geti_revoke'

    def _entid(self):
        entid = ELGeti.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self):
        return u'%s的吊销信息' % self.entid


# 个体户注销信息
class ELGetiCancel(ELBaseModel):
    entobj = models.ForeignKey('company.ELGeti', verbose_name='所属个体户', db_column='entid', default=0,
                               related_name='c_geti_cancel', to_field='entid')
    CANREA = models.CharField('注销原因', max_length=3, null=True, blank=True, choices=cd16_dict, db_index=True)
    CANDATE = models.DateField('注销日期', null=True, blank=True)
    CANAUTH = models.CharField('注销机关', max_length=200, null=True, blank=True)
    SANDOCNO = models.CharField('批准文号', max_length=200, null=True, blank=True)
    BLICREVORINUM = models.FloatField('营业执照缴销正本数', null=True, blank=True)
    BLICREVORINO = models.CharField('营业执照缴销正本编号', max_length=36, null=True, blank=True)
    BLICREVDUPCONUM = models.FloatField('营业执照缴销副本数', null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户注销信息'
        verbose_name_plural = '个体户注销信息'
        app_label = "company"
        db_table = 'geti_cancel'

    def _entid(self):
        entid = ELGeti.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self):
        return u'%s的注销信息' % self.entid


# 个体户注册变更记录
class ELGetiModify(ELBaseModel):
    entobj = models.ForeignKey('company.ELGeti', verbose_name='所属个体户', db_column='entid', default=0,
                               related_name='c_geti_modify', to_field='entid')
    ALTITEM = models.CharField('变更事项', max_length=3, null=True, blank=True, choices=cd04_dict)
    ALTBE = models.TextField('变更前内容', null=True, blank=True)
    ALTAF = models.TextField('变更后内容', null=True, blank=True)
    ALTDATE = models.DateField('变更日期', null=True, blank=True)
    ALTTIME = models.IntegerField('变更次数', null=True, blank=True)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户注册变更'
        verbose_name_plural = '个体户注册变更'
        app_label = "company"
        db_table = 'geti_modify'

    def _entid(self):
        entid = ELGeti.objects.filter(entid=self.entobj_id).first()
        if entid:
            return entid
        return ""

    _entid.short_description = "所属企业"

    entid = property(_entid)

    def __unicode__(self):
        return u'%s的注册变更' % self.entid


# 个体工商户许可证信息
class ELGetiLicence(EntIdable):
    LIC_ID = models.CharField('许可文件ID', max_length=50)
    LICNO = models.CharField('许可文件编号', max_length=200, null=True, blank=True)
    LICNAME_id = CrossForeignCharField('许可文件', null=True, blank=True, max_length=6, db_column='LICNAME')
    VALFORM = models.DateField('有效期自', null=True, blank=True)
    VALTO = models.DateField('有效期至', null=True, blank=True)
    LICANTH = models.CharField('许可机关', max_length=200, null=True, blank=True)
    LICSTATE = models.CharField('许可文件状态', max_length=2, null=True, blank=True, choices=ca26_dict)
    updated = models.DateTimeField('更新时间', null=True, blank=True)

    class Meta:
        verbose_name = '个体户许可信息'
        verbose_name_plural = '个体户许可信息'
        app_label = "companyplus"
        db_table = 'company_certificate_geti'

    def __unicode__(self):
        return u'%s的许可信息' % self.entid

    def _licname(self):
        the_licname = list(ELCA25.objects.filter(code=self.LICNAME_id).values_list("name", flat=True))
        if len(the_licname):
            return the_licname[0]
        return ""

    _licname.short_description = "许可证书"

    LICNAME = property(_licname)


# 个体户id映射
class ELGetiPripid(ELBaseModel):
    entid = models.IntegerField('所属个体户', primary_key=True)
    PRIPID = models.CharField('总局PRIPID', max_length=36, null=True, blank=True, db_index=True)

    class Meta:
        verbose_name = '总局个体id映射'
        verbose_name_plural = '总局个体id映射'
        app_label = "companyplus"
        db_table = 'company_id_geti_pripid'

    def __unicode__(self):
        return u'%s的id映射' % self.entid


models_geti_imported = 0  # 仅供主model引用的虚变量
